#include "HuffTree.h"

void initHuff(HuffTree* H)
{
	H->root = 0;
}

void constructTree(HuffTree* H, HuffNo** leafNode, int leafSize)
{
	HuffNo *no1, *no2 , *raiz;
	int codigoHuff =0;

	while(leafSize > 1)
	{
		//ordena vetor ate leafSize
		ordena(leafNode, leafSize);

		no1 = leafNode[leafSize-1];
		no2 = leafNode[leafSize-2];
		raiz = (HuffNo*)malloc(1*sizeof(HuffNo));
		raiz->folha =0; //nao eh folha
		raiz->frequencia = no1->frequencia + no2->frequencia;
		raiz->tamanho = 0;
		raiz->codigoHuffTam= 0;
		raiz->codigoHuff = 0;
		raiz->dir = no1;
		raiz->esq = no2;

		leafNode[leafSize -2] = raiz; //substitui no vetor

		leafSize--;
	}

	H->root = leafNode[0];
	printf("frequencia -- %d\n",H->root->frequencia );

	createCodeHuff(H->root, &codigoHuff, 0);
}

void createCodeHuff(HuffNo* root, int* code, int length)
{
	if(root)
	{
		if(root->folha == 0) //nao eh no folha
		{
			*code = *code << 1;
			*code = *code | 1;
			createCodeHuff(root->esq, code, length+1);
			*code = *code >>1;

			*code = *code << 1;
			createCodeHuff(root->dir, code, length+1);
			*code = *code >>1;
			printf("teste");
		}
		else //eh no folha
		{
			//copia para root o valor de code
			root->codigoHuff = *code;
			printf("huffcode: %d\n", *code);
			root->codigoHuffTam = length;
			printf("huffcodelength: %d\n", length);
		}
	}
}

void ordena(HuffNo** leafNode, int leafSize)
{
	int i, j;
	HuffNo *aux;
	for(i=0; i< leafSize; i++)
	{
		for(j=0; j< leafSize-1; j++)
		{
			if(leafNode[j]->frequencia < leafNode[j+1]->frequencia)
			{
				aux = leafNode[j+1];
				leafNode[j+1] = leafNode[j];
				leafNode[j] = aux;
			}
		}
	}
}

int getCodeHuff(HuffTree* H, int tamanho, int* codeHuffTam) //retorna o cogigo huffman para um tamanho
{
	int codeHuff =512;
	getCodeHuffRec(H->root, tamanho, &codeHuff, codeHuffTam);

	return codeHuff;
}

void getCodeHuffRec(HuffNo* root, int tamanho, int* codeHuff, int* codeHuffTam)
{
	if(root)
	{
		if(root->folha == 0) //nao eh folha
		{
			getCodeHuffRec(root->esq, tamanho, codeHuff, codeHuffTam);
			getCodeHuffRec(root->dir, tamanho, codeHuff, codeHuffTam);
		}
		else //eh folha
		{
			if(root->tamanho == tamanho)
			{
				*codeHuff = root->codigoHuff;
				*codeHuffTam = root->codigoHuffTam;
			}
		}

	}
}

